#pragma once
#include<iostream>
#include<assert.h>
#include<vector>
using namespace std;

enum Colour
{
	RED,
	BLACK
};

template<class T>
struct RBTreeNode
{
	T _data;

	RBTreeNode<T>* _left;
	RBTreeNode<T>* _right;
	RBTreeNode<T>* _parent;
	Colour _col;

	RBTreeNode(const T& data)
		:_data(data)
		, _left(nullptr)
		, _right(nullptr)
		, _parent(nullptr)
	{}
};

template<class T>
struct RBTreeIterator
{
	typedef RBTreeNode<T> Node;
	typedef RBTreeIterator<T> Self;

	Node* _node;

	RBTreeIterator(Node* node)
		:_node(node)
	{}

	Self& operator++()
	{
		if (_node->_right)
		{
			//右不为空，右子树最左节点就是中序下一个
			Node* leftMost = _node->_right;
			while (leftMost->_left)
			{
				leftMost = leftMost->_left;
			}
			_node = leftMost;
		}
		else
		{
			Node* cur = _node;
			Node* parent = cur->_parent;
			while (parent && cur == parent->_right)
			{
				cur = parent;
				parent = cur->_parent;
			}
			_node = parent;
		}
		return *this;
	}

	T& operator*()
	{
		return _node->_data;
	}

	T& operator->()
	{
		return &_node->_data;
	}

	bool operator!=(const Self& s)
	{
		return _node != s._node;
	}
};

// K：给find、erase使用的
// T：给Insert Node 用的
template<class K, class T, class KeyOfT>
class RBTree
{
	typedef RBTreeNode<T> Node;
public:
	typedef RBTreeIterator<T> Iterator;

	Iterator Begin()
	{
		Node* leftMost = _root;
		while (leftMost && leftMost->_left)
		{
			leftMost = leftMost->_left;
		}

		return Iterator(leftMost);
	}

	Iterator End()
	{
		return Iterator(nullptr);
	}


	RBTree() = default;

	//RBTree(const RBTree<K, T, KeyOfT >& t)
	RBTree(const RBTree& t)//可直接简写成类名
	{
		_root = Copy(t._root);
	}

	//RBTree<K, T, KeyOfT >& operator=(RBTree<K, T, KeyOfT> t)
	RBTree& operator=(RBTree t)
	{
		swap(_root, t._root);
		return *this;
	}

	~RBTree()
	{
		Destroy(_root);
		_root = nullptr;
	}

	// 在AVL树中插入值为kv的节点
	bool Insert(const T& data)
	{
		if (_root == nullptr)
		{
			_root = new Node(data);
			return true;
		}

		KeyOfT kot;

		Node* parent = nullptr;
		Node* cur = _root;
		while (cur)
		{
			//if (cur->_data < data)// pair比较大小不是按照key比较的
			                       // first比完，second再比，其中一个小就小
			if (kot(cur->_data) < kot(data))
			{                     
				parent = cur;
				cur = cur->_right;
			}
			else if (kot(cur->_data) > kot(data))
			{
				parent = cur;
				cur = cur->_left;
			}
			else
			{
				//找到相同的数，返回false
				return false;
			}
		}
		//插入新节点，颜色给红色
		cur = new Node(data);
		cur->_col = RED;
		if (kot(parent->_data) < kot(data))
		{
			parent->_right = cur;
		}
		else
		{
			parent->_left = cur;
		}
		cur->_parent = parent;//与parent链接

		while (parent && parent->_col == RED)//父亲存在且为红
		{
			//     g
			//  p     u
			//不关注c插入在p的左/右方向
			Node* grandfather = parent->_parent;
			if (parent == grandfather->_left)//
			{
				//u存在且为红->变色再继续往上更新
				Node* uncle = grandfather->_right;
				if (uncle && uncle->_col == RED)//u 存在且为红
				{
					parent->_col = uncle->_col = BLACK;// p、u变为黑
					grandfather->_col = RED;//g变为红

					//继续往上更新
					cur = grandfather;
					parent = cur->_parent;
				}
				else
				{
					//u存在且为黑 或 不存在 -> 旋转 + 变色
					// 关注c插入在p的左/右方向
						//    g
					   //  p     u
					  // c
					  // 单旋
					if (cur == parent->_left)
					{
						RotateR(grandfather);
						parent->_col = BLACK;
						grandfather->_col = RED;
					}
					else
					{
						//    g
					   //  p     u
					  //     c
					  //双旋
						RotateL(parent);
						RotateR(grandfather);
						cur->_col = BLACK;
						grandfather->_col = RED;
					}

					break;
				}
			}
			else//parent == grandfather->_right
			{
				//     g
				//  u     p 
				//不关注c插入在p的左/右方向

				Node* uncle = grandfather->_left;
				if (uncle && uncle->_col == RED)
				{
					parent->_col = uncle->_col = BLACK;
					grandfather->_col = RED;

					//继续往上更新
					cur = grandfather;
					parent = cur->_parent;
				}
				else
				{
					//u存在且为黑 或 不存在 -> 旋转 + 变色
					// 关注c插入在p的左/右方向
					//    g
				   //  u     p
				  //           c
				  // 单旋
					if (cur == parent->_right)
					{
						RotateL(grandfather);
						parent->_col = BLACK;
						grandfather->_col = RED;
					}
					else
					{
						//    g
					   //  u     p
					  //       c
					  //双旋
						RotateR(parent);
						RotateL(grandfather);
						cur->_col = BLACK;
						grandfather->_col = RED;
					}

					break;
				}
			}
		}
		//1、parent不存在，cur就是根了，出去之后把根处理成黑的
		//2、parent存在，且为黑
		//3、parent存在，且为红，继续循环处理

		_root->_col = BLACK;//无论什么情况都把根变黑

		return true;
	}

	Node* Find(const K& key)// 不能用 T ，如果是map时，T是一个pair<K,V>,中英文都知道了，没必要找
	{
		Node* cur = _root;
		while (cur)
		{
			if (cur->_kv.first < key)
			{
				cur = cur->_right;
			}
			else if (cur->_kv.first > key)
			{
				cur = cur->_left;
			}
			else
			{
				return cur;
			}
		}
		return nullptr;
	}

	int Height()
	{
		return _Height(_root);
	}

	void InOrder()
	{
		_InOrder(_root);
		cout << endl;
	}

	int Size()
	{
		return _Size(_root);
	}

	bool IsBalance()
	{
		if (_root == nullptr)
		{
			return true;
		}

		if (_root->_col == RED)
		{
			return false;
		}

		//找一条路径作为参考值（最左路径 或 最右路径）
		int refNum = 0;
		Node* cur = _root;
		while (cur)
		{
			if (cur->_col == BLACK)
			{
				++refNum;
			}

			cur = cur->_left;//走最左路径
		}

		return Check(_root, 0, refNum);
	}

private:
	bool Check(Node* root, int blackNum, const int refNum)
	{
		if (root == nullptr)//结束条件
		{
			cout << blackNum << endl;
			if (refNum != blackNum)
			{
				cout << "存在黑色节点的数量不相等的路径" << endl;
				return false;
			}

			return true;
		}

		if (root->_col == RED && root->_parent->_col == RED)
		{
			cout << root->_kv.first << "存在连续的红色节点" << endl;
			return false;
		}

		if (root->_col == BLACK)
		{
			blackNum++;
		}

		//前序遍历
		return Check(root->_left, blackNum, refNum)
			&& Check(root->_right, blackNum, refNum);
	}


	int _Size(Node* root)
	{
		//左边+右边
		return root == nullptr ? 0 : _Size(root->_left) + _Size(root->_right) + 1;
	}

	void _InOrder(Node* root)
	{
		if (root == nullptr)
		{
			return;
		}

		_InOrder(root->_left);
		cout << root->_kv.first << ":" << root->_kv.second << endl;
		_InOrder(root->_right);
	}

	int _Height(Node* root)
	{
		if (root == nullptr)
		{
			return 0;
		}
		int leftHeight = _Height(root->_left);
		int rightHeight = _Height(root->_right);

		return leftHeight > rightHeight ? leftHeight + 1 : rightHeight + 1;
	}

	// 右单旋
	void RotateR(Node* parent)
	{
		Node* subL = parent->_left;
		Node* subLR = subL->_right;

		parent->_left = subLR;
		if (subLR)
			subLR->_parent = parent;

		Node* parentParent = parent->_parent;

		subL->_right = parent;
		parent->_parent = subL;

		//判断是否为根？
		if (parentParent == nullptr)
		{
			_root = subL;
			subL->_parent = nullptr;
		}
		else
		{
			if (parent == parentParent->_left)
			{
				parentParent->_left = subL;
			}
			else
			{
				parentParent->_right = subL;
			}

			subL->_parent = parentParent;
		}
	}

	// 左单旋
	void RotateL(Node* parent)
	{
		Node* subR = parent->_right;
		Node* subRL = subR->_left;

		parent->_right = subRL;
		if (subRL)
			subRL->_parent = parent;

		Node* parentParent = parent->_parent;

		subR->_left = parent;
		parent->_parent = subR;

		if (parentParent == nullptr)
		{
			_root = subR;
			subR->_parent = nullptr;
		}
		else
		{
			if (parent == parentParent->_left)
			{
				parentParent->_left = subR;
			}
			else
			{
				parentParent->_right = subR;
			}
			subR->_parent = parentParent;
		}
	}

	void Destroy(Node* root)
	{
		if (root == nullptr)
			return;

		Destroy(root->_left);
		Destroy(root->_right);
		delete root;
	}

	Node* Copy(Node* root)
	{
		if (root == nullptr)
			return nullptr;

		Node* newRoot = new Node(root->_kv);
		newRoot->_left = Copy(root->_left);
		newRoot->_right = Copy(root->_right);

		return newRoot;
	}

private:
	Node* _root = nullptr;
};

//void RBTreetest1()
//{
//	RBTree<int, int> t;
//	//int a[] = { 16,3,7,11,9,26,18,14,15 };
//	int a[] = { 4,2,6,1,3,5,15,7,16,14 };
//	for (auto e : a)
//	{
//		/*	if (e == 11)
//			{
//				int i = 0;
//			}*/
//		t.Insert({ e,e });
//		//cout << e << "->" << t.IsBalance() << endl;
//
//	}
//	t.InOrder();
//	cout << t.IsBalance() << endl;
//
//}
//
//void RBTreetest2()
//{
//	const int N = 100000;
//	vector<int> v;
//	v.reserve(N);
//	srand(time(0));
//
//	for (size_t i = 0; i < N; i++)
//	{
//		v.push_back(rand());
//		//cout << v.back() << endl;
//	}
//
//	size_t begin2 = clock();
//	RBTree<int, int> t;
//	for (auto e : v)
//	{
//		t.Insert(make_pair(e, e));
//		//cout << "Insert:" << e << "->" << t.IsBalance() << endl;
//	}
//	size_t end2 = clock();
//
//	cout << "Insert:" << end2 - begin2 << endl;
//	//cout << t.IsBalance() << endl;
//
//	cout << "Height:" << t.Height() << endl;
//	cout << "Size:" << t.Size() << endl;
//
//	size_t begin1 = clock();
//	// 确定在的值
//	for (auto e : v)
//	{
//		t.Find(e);
//	}
//
//	// 随机值
//	for (size_t i = 0; i < N; i++)
//	{
//		t.Find((rand() + i));
//	}
//
//	size_t end1 = clock();
//
//	cout << "Find:" << end1 - begin1 << endl;
//}
